package com.cswnode.Controller;

import com.cswnode.Entity.DiscussPost;
import com.cswnode.Entity.Page;
import com.cswnode.Entity.User;
import com.cswnode.Service.DiscussPostService;
import com.cswnode.Service.LikeService;
import com.cswnode.Service.MessageService;
import com.cswnode.Service.UserService;
import com.cswnode.Util.Constant;
import com.cswnode.Util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;

    @GetMapping("/")
    public String getIndexPage(Model model, Page page){
        page.setRows(discussPostService.findDiscussPostRow(0));
        //获取所有的帖子
        List<DiscussPost> discussPost = discussPostService.findDiscussPost(0, page.getOffset(), page.getLimit());
        //创建list集合，用来存储帖子以及对应的用户
        List<Map<String,Object>> discussPosts = new ArrayList<>();
        if (discussPost != null){
            for (DiscussPost post : discussPost) {
                //创建存储的map
                Map map = new HashMap();
                //将帖子添加到map集合
                map.put("like",likeService.findEntityLikeCount(Constant.ENTITY_TYPE_POST,post.getId()));
                map.put("post",post);
                //获取该帖子对应的user
                User userById = userService.findUserById(post.getUserId());
                //将用户添加到map集合
                map.put("user",userById);
                //将帖子以及对应的用户集合添加到list里，返回到前端
                discussPosts.add(map);

            }
        }
        User user = hostHolder.getUser();
        if (user != null){
            int LetterUnreadCount = messageService.findsUnreadMessage(user.getId(),null);
            model.addAttribute("LetterUnreadCount",LetterUnreadCount);
        }


        model.addAttribute("post",discussPosts);
        return "index";
    }

    @GetMapping("/error")
    public String toErrorPage(){
        return "/error/500";
    }


}
